<template>
  <div 
    class="chart-container"
    :ref="el => setChartRef(el)"
    :data-chart-id="id"
    style="width: 100%; height: 100%;"
  ></div>
</template>

<script setup>
import { onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  id: {
    type: [String, Number],
    required: true
  },
  type: {
    type: String,
    required: true
  },
  data: {
    type: Array,
    default: () => []
  },
  options: {
    type: Object,
    default: () => ({})
  }
})

let chartInstance = null

// 生成图表配置
const generateChartOption = () => {
  let option = {
    animation: true,
    title: {
      text: props.options.title,
      left: 'center',
      textStyle: { color: '#fff' }
    }
  }

  // 根据不同类型生成对应的图表配置
  if (props.type.startsWith('bar-')) {
    option = {
      ...option,
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      grid: {
        top: '15%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: props.options.categories || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        axisLine: { lineStyle: { color: '#fff' } }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
      },
      series: [{
        type: 'bar',
        data: props.data || [120, 200, 150, 80, 70, 110, 130],
        barWidth: props.options.barWidth || 30,
        itemStyle: {
          color: props.options.color || '#409EFF'
        }
      }]
    }
    
    // 特殊处理堆叠柱状图
    if (props.type === 'bar-stack' && Array.isArray(props.data) && props.data.length > 0 && Array.isArray(props.data[0])) {
      option.series = props.data.map((data, index) => ({
        type: 'bar',
        stack: 'total',
        data: data,
        itemStyle: {
          color: props.options.colors?.[index] || ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'][index % 5]
        }
      }))
    }
    
    // 特殊处理横向条形图
    if (props.type === 'bar-horizontal') {
      option.xAxis = { type: 'value', axisLine: { lineStyle: { color: '#fff' } }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } }
      option.yAxis = { type: 'category', data: props.options.categories || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], axisLine: { lineStyle: { color: '#fff' } } }
    }
  } else if (props.type.startsWith('line-')) {
    option = {
      ...option,
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'cross' }
      },
      grid: {
        top: '15%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: props.options.categories || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        axisLine: { lineStyle: { color: '#fff' } }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
      },
      series: [{
        type: 'line',
        data: props.data || [120, 200, 150, 80, 70, 110, 130],
        smooth: props.options.smooth !== false,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: { color: props.options.color || '#409EFF' },
        lineStyle: { width: 2 }
      }]
    }
    
    // 特殊处理面积图
    if (props.type === 'line-area') {
      option.series[0].areaStyle = {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: props.options.color || '#409EFF' },
          { offset: 1, color: 'rgba(64,158,255,0.1)' }
        ])
      }
    }
  } else if (props.type.startsWith('pie-')) {
    option = {
      ...option,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        textStyle: { color: '#fff' }
      },
      series: [{
        name: props.options.title || '饼图',
        type: 'pie',
        radius: props.options.radius || '50%',
        center: props.options.center || ['50%', '50%'],
        data: props.data || [
          { value: 335, name: '直接访问' },
          { value: 310, name: '邮件营销' },
          { value: 234, name: '联盟广告' },
          { value: 135, name: '视频广告' },
          { value: 1548, name: '搜索引擎' }
        ],
        label: {
          show: props.options.showLabel !== false,
          color: '#fff',
          formatter: '{b}: {c} ({d}%)'
        },
        itemStyle: {
          borderRadius: props.options.borderRadius || 0
        }
      }]
    }
    
    // 特殊处理环形图
    if (props.type === 'pie-doughnut') {
      option.series[0].radius = ['40%', '70%']
    }
  } else if (props.type.startsWith('ring-')) {
    option = {
      ...option,
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: '5%',
        textStyle: { color: '#fff' }
      },
      series: [{
        name: props.options.title || '环形图',
        type: 'pie',
        radius: props.options.radius || ['40%', '70%'],
        center: props.options.center || ['50%', '50%'],
        data: props.data || [
          { value: 335, name: '直接访问' },
          { value: 310, name: '邮件营销' },
          { value: 234, name: '联盟广告' },
          { value: 135, name: '视频广告' },
          { value: 1548, name: '搜索引擎' }
        ],
        label: {
          show: props.options.showLabel !== false,
          color: '#fff',
          formatter: '{b}: {c} ({d}%)'
        }
      }]
    }
  } else if (props.type.startsWith('scatter-')) {
    option = {
      ...option,
      tooltip: {
        trigger: 'item',
        formatter: function (params) {
          return `${params.seriesName}<br/>X: ${params.value[0]}<br/>Y: ${params.value[1]}`
        }
      },
      grid: {
        top: '15%',
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#fff' } },
        splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
      },
      series: [{
        name: props.options.title || '散点图',
        type: 'scatter',
        data: props.data || [
          [10.0, 8.04],
          [8.0, 6.95],
          [13.0, 7.58],
          [9.0, 8.81],
          [11.0, 8.33]
        ],
        symbolSize: props.options.symbolSize || 10,
        itemStyle: {
          color: props.options.color || '#409EFF'
        }
      }]
    }
  } else if (props.type === 'bar') {
    option = {
      ...option,
      xAxis: { type: 'category', data: ['A', 'B', 'C', 'D', 'E', 'F', 'G'], axisLine: { lineStyle: { color: '#fff' } } },
      yAxis: { type: 'value', axisLine: { lineStyle: { color: '#fff' } }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
      series: [{
        type: 'bar',
        data: props.data || [120, 200, 150, 80, 70, 110, 130],
        barWidth: props.options.barWidth || 30,
        itemStyle: { color: props.options.color || '#409EFF' }
      }]
    }
  } else if (props.type === 'line') {
    option = {
      ...option,
      xAxis: { type: 'category', data: ['A', 'B', 'C', 'D', 'E', 'F', 'G'], axisLine: { lineStyle: { color: '#fff' } } },
      yAxis: { type: 'value', axisLine: { lineStyle: { color: '#fff' } }, splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } } },
      series: [{
        type: 'line',
        data: props.data || [120, 200, 150, 80, 70, 110, 130],
        itemStyle: { color: props.options.color || '#409EFF' }
      }]
    }
  } else if (props.type === 'pie') {
    option = {
      ...option,
      series: [{
        type: 'pie',
        data: props.data || [
          { value: 335, name: 'A' },
          { value: 310, name: 'B' },
          { value: 234, name: 'C' },
          { value: 135, name: 'D' },
          { value: 1548, name: 'E' }
        ],
        label: { show: true, color: '#fff', formatter: '{b}: {c} ({d}%)' }
      }]
    }
  }

  return option
}

// 初始化图表
const initChart = (el) => {
  if (el) {
    // 销毁旧的实例
    if (chartInstance) {
      chartInstance.dispose()
    }

    // 创建新的实例
    chartInstance = echarts.init(el, 'dark')
    updateChart()

    // 添加窗口大小变化监听
    const resizeObserver = new ResizeObserver(() => {
      chartInstance?.resize()
    })
    resizeObserver.observe(el)

    // 保存 resizeObserver 实例以便清理
    el._resizeObserver = resizeObserver
  }
}

// 更新图表
const updateChart = () => {
  if (chartInstance) {
    const option = generateChartOption()
    chartInstance.setOption(option, true)
  }
}

// 设置图表容器引用
const setChartRef = (el) => {
  initChart(el)
}

// 监听数据变化
watch(() => [props.data, props.options], () => {
  updateChart()
}, { deep: true })

// 组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 